package cn.edu.swu.toy;

import cn.edu.swu.core.BasicServlet;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.util.List;

@WebServlet(urlPatterns = "/api/toy/*")
public class ToyApi extends BasicServlet {

    private ToyService toyService = null;

    public void init(ServletConfig config) {
        ToyRepo repo = new ToyRepo();
        toyService = new ToyService();
        toyService.setRepo(repo);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        this.methodRoute(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        this.methodRoute(request, response);
    }

    private void methodRoute(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        String uri = request.getRequestURI();
        String method = uri.substring(uri.lastIndexOf("/") + 1);
        if (method.equals("list")) {
            this.list(request, response);
        } else if (method.equals("add")) {
            this.add(request, response);
        }
    }

    public void list(HttpServletRequest request, HttpServletResponse response) throws ServletException{
        try {
            List<Toy> toys = this.toyService.getAll();
            this.responseJson(response, true, toys);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException{
        try {
            String json = this.getRequestBody(request);
            System.out.println(json);
            objectMapper.setDateFormat(dateFormatter);
            Toy toy = objectMapper.readValue(json, Toy.class);
            this.toyService.save(toy);
            this.responseJson(response, true, toy);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
